// _Test8_FlipImage.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <stdio.h>

bool flip_vertical = false;
bool flip_horizontal = false;
bool invalidate = true;

/*
* press 'h' to flip the image horizontally
* press 'v' to flip the image vertically
*/


int main(int argc, char** argv){	// change main1 -> main

	/* variable declaration */
	IplImage *image, *flipImage = NULL;
	uchar *data, *flipdata;
	int width, height, step, channels, depth, flip_x, flip_y;
	int key;

	if(argc < 2){
		printf("Usage: main <image-file-name>\n\7");
	}

	image = cvLoadImage(argv[1]);
	if(!image){
		printf("Could not load the image file: %s\n", argv[1]);
		exit(0);
	}

	width = image->width;
	height = image->height;
	channels = image->nChannels;
	step = image->widthStep;
	depth = image->depth;

	printf("Processing a %dx%d image with %d channels\n", height, width, channels);

	//cvNamedWindow("Original Image", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Flipped Image", CV_WINDOW_AUTOSIZE);

	while(true){
		if(invalidate){
			invalidate = false;
			if(flipImage != NULL){
				cvReleaseImage(&flipImage);
			}

			flipImage = cvCreateImage(cvGetSize(image), depth, channels);
			data = (uchar*) image->imageData;
			flipdata = (uchar*) flipImage->imageData;

			for(int i = 0; i < height; i++){
				for(int j = 0; j < width; j++){
					for(int k = 0; k < channels; k++){					

						if(flip_vertical){
							flip_y = (height - i);
						} else {
							flip_y = i;
						}

						if(flip_horizontal){
							flip_x = (width - j);
						} else {
							flip_x = j;
						}

						flipdata[i * step + j * channels + k] = 
							data[flip_y * step + flip_x * channels + k];
					}
				}
			}
		}

		//	cvShowImage("Original Image", image);
		cvShowImage("Flipped Image", flipImage);

		/* process key event */
		key = cvWaitKey(0);
		switch (key){
		case 'h':
			flip_horizontal = !flip_horizontal;
			invalidate = true;
			break;
		case 'v':
			flip_vertical = !flip_vertical;
			invalidate = true;
			break;
		case 27:
			return 0;
			break;
		default:
			printf("Stupid\n");
			break;
		}
	}
	return 0;
}